﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Model.ViewModels;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.StaffApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.StaffAPI
{
    [Description("API-中介")]
    [ApiAuthentication]
    public class StaffOrganizationController : BaseApiController
    {
        public IIntermediaryContract IntermediaryContract { get; set; }
        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }
        public IUsersContract UsersContract { get; set; }
        public IUsersLoginContract UsersLoginContract { get; set; }
        public IUsersRolesContract UsersRolesContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IStaffRolesContract StaffRolesContract { get; set; }
        public IAgentCityContract AgentCityContract { get; set; }
        public IIntermediaryStatisticsContract IntermediaryStatisticsContract { get; set; }
        public IInSideModelContract InSideModelContract { get; set; }
        public IOutSideModelContract OutSideModelContract { get; set; }
        public ISideModuleContract SideModuleContract { get; set; }
        public IDepartmentContract DepartmentContract { get; set; }
        public IStaffMessagesContract StaffMessagesContract { get; set; }

        //门店列表==========================================================================================================

        [Description("API-门店列表")]
        public IHttpActionResult ttGetBuildingsList([FromBody]IntermediarysParamsModel entity)
        {

            var query = IntermediaryContract.Entities;
            int staffid = BaseWebApiExt.GetStaffIDByToken();

            //全部创建的
            int createNumber_Total = query.Count(p => IntermediaryStaffContract.Entities.Count(pp => pp.IntermediaryID == p.Id && pp.StaffID == staffid) > 0);

            //30天内创建的
            DateTime startDate_30Day = DateTime.Now.AddDays(-1 * 30);
            DateTime endDate_30Day = DateTime.Now;
            int createNumber_30Day = query.Where(m => m.CreateTime >= startDate_30Day && m.CreateTime <= endDate_30Day && IntermediaryStaffContract.Entities.Count(pp => pp.IntermediaryID == m.Id && pp.StaffID == staffid) > 0).Count();

            //7天内创建的
            DateTime startDate_7Day = DateTime.Now.AddDays(-1 * 7);
            DateTime endDate_7Day = DateTime.Now;
            int createNumber_7Day = query.Where(m => m.CreateTime >= startDate_7Day && m.CreateTime <= endDate_7Day && IntermediaryStaffContract.Entities.Count(pp => pp.IntermediaryID == m.Id && pp.StaffID == staffid) > 0).Count();


            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(m => m.Name.Contains(entity.KeyWord) || m.Address.Contains(entity.KeyWord));
            }

            //指定天数
            if (entity.DayCount > 0)
            {
                DateTime startDate = DateTime.Now.AddDays(-1 * entity.DayCount);
                DateTime endDate = DateTime.Now;
                query = query.Where(m => m.CreateTime >= startDate && m.CreateTime <= endDate);
            }


            //看管理员自己的
            if (entity.IsOwned == 1)
            {
                //获取StaffID
                //管理员所属门店ID
                List<int> intermediaryIDList = IntermediaryStaffContract.Entities.Where(m => m.StaffID == staffid).Select(m => m.IntermediaryID).Distinct().ToList();
                query = query.Where(m => intermediaryIDList.Contains(m.Id));
            }

            //维护限定时间
            DateTime setCareTime = DateTime.Now.AddDays(-7);

            var list = (from m in query
                        join n in IntermediaryStatisticsContract.Entities
                        on m.Id equals n.IntermediaryID into temp
                        from tt in temp.DefaultIfEmpty()
                        select new IntermediarysListModel
                        {
                            Id = m.Id,
                            Name = m.Name,
                            Address = m.Address,
                            LicenceImage = m.LicenceImage,
                            CreateTime = m.CreateTime,

                            IsShowRedIco = (m.CreatedTime < setCareTime) ? 2 : 1,//维护图标
                            Phone = (from m2 in UsersContract.Entities
                                     join m3 in UsersRolesContract.Entities
                                     on m2.Id equals m3.UserID
                                     where m2.IntermediaryID == m.Id && m2.IsDeleted == false && m3.IntermediaryRoleID == 1
                                     select m2.Phone).FirstOrDefault(),

                            UsersNumber = UsersContract.Entities.Where(m1 => m1.IntermediaryID == m.Id && m1.IsDeleted == false).Count(),
                            CareNumber = OutSideModelContract.Entities.Count(p => p.OutSideType == 2 && p.InterfixID == m.Id),//维护次数
                            LastCareTime = m.CreatedTime,//最新维护时间

                            LoginNumber_Total = (tt == null) ? 0 : tt.LoginNumber_Total,
                            LoginNumber_30Day = (tt == null) ? 0 : tt.LoginNumber_30Day,
                            LoginNumber_7Day = (tt == null) ? 0 : tt.LoginNumber_7Day,

                            FilingNumber_Total_Newhouse = (tt == null) ? 0 : tt.FilingNumber_Total_Newhouse,
                            BandSawNumber_Total_Newhouse = (tt == null) ? 0 : tt.BandSawNumber_Total_Newhouse,
                            SuccessNumber_Total_Newhouse = (tt == null) ? 0 : tt.SuccessNumber_Total_Newhouse
                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.CreateTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<IntermediarysListModel>().AsQueryable();// null;

            List<IntermediarysListModel> arr = list.ToList();

            ExtMethod.HandleListValue<IntermediarysListModel>(arr);

            var result = new AjaxResult("成功", AjaxResultType.Success, new { List = arr, CreateNumber_Total = createNumber_Total, CreateNumber_30Day = createNumber_30Day, CreateNumber_7Day = createNumber_7Day });
            return Token(result, "");

        }


        [Description("API-门店详情")]
        public IHttpActionResult ttGetBuildingsModel([FromBody]Intermediary entity)
        {

            var model = IntermediaryContract.GetByKey(entity.Id);

            if (model != null)
            {
                ExtMethod.HandleModelValue<Intermediary>(model);//处理null

                var query = new IntermediaryInfoModel();

                //基本信息          
                query.Id = model.Id;
                query.Name = model.Name;
                query.Address = model.Address;
                query.LicenceImage = model.LicenceImage;

                //店主
                var userModel = (from m in UsersContract.Entities
                                 join n in UsersRolesContract.Entities
                                 on m.Id equals n.UserID
                                 where m.IntermediaryID == model.Id && m.IsDeleted == false && n.IntermediaryRoleID == 1
                                 select new
                                 {
                                     Name = m.Name,
                                     Phone = m.Phone
                                 }).FirstOrDefault();

                if (userModel != null)
                {
                    query.UserName = userModel.Name;
                    query.Phone = userModel.Phone;
                }
                else
                {
                    query.UserName = "";
                    query.Phone = "";
                }

                //经纪人数量
                query.UsersNumber = UsersContract.Entities.Where(m => m.IntermediaryID == model.Id && m.IsDeleted == false).Count();

                //门店信息统计
                var intermediaryStatisticsModel = IntermediaryStatisticsContract.Entities.Where(m => m.IntermediaryID == model.Id).FirstOrDefault();

                //活跃度
                if (intermediaryStatisticsModel != null)
                {
                    query.LoginNumber_Total = intermediaryStatisticsModel.LoginNumber_Total;
                    query.LoginNumber_30Day = intermediaryStatisticsModel.LoginNumber_30Day;
                    query.LoginNumber_7Day = intermediaryStatisticsModel.LoginNumber_7Day;
                }
                else
                {
                    query.LoginNumber_Total = 0;
                    query.LoginNumber_30Day = 0;
                    query.LoginNumber_7Day = 0;
                }

                //项目状态
                query.FilingNumber_Total = 0;
                query.BandSawNumber_Total = 0;
                query.SuccessNumber_Total = 0;

                if (intermediaryStatisticsModel != null)
                {
                    query.FilingNumber_Total += intermediaryStatisticsModel.FilingNumber_Total_Newhouse;
                    query.FilingNumber_Total += intermediaryStatisticsModel.FilingNumber_Total_LowPriceHouse;
                    query.FilingNumber_Total += intermediaryStatisticsModel.FilingNumber_Total_Decoration;
                    query.FilingNumber_Total += intermediaryStatisticsModel.FilingNumber_Total_Finance;

                    query.BandSawNumber_Total += intermediaryStatisticsModel.BandSawNumber_Total_Newhouse;
                    query.BandSawNumber_Total += intermediaryStatisticsModel.BandSawNumber_Total_LowPriceHouse;
                    query.BandSawNumber_Total += intermediaryStatisticsModel.BandSawNumber_Total_Decoration;
                    query.BandSawNumber_Total += intermediaryStatisticsModel.BandSawNumber_Total_Finance;

                    query.SuccessNumber_Total += intermediaryStatisticsModel.SuccessNumber_Total_Newhouse;
                    query.SuccessNumber_Total += intermediaryStatisticsModel.SuccessNumber_Total_LowPriceHouse;
                    query.SuccessNumber_Total += intermediaryStatisticsModel.SuccessNumber_Total_Decoration;
                    query.SuccessNumber_Total += intermediaryStatisticsModel.SuccessNumber_Total_Finance;
                }

                //维护次数
                query.CareNumber = 0;

                //类别销售
                query.IntermediaryStaffShowList = new List<IntermediaryStaffShowModel>();

                //获取StaffID
                int staffid = BaseWebApiExt.GetStaffIDByToken();

                //角色集合
                var staffRolesList = StaffRolesContract.Entities.Where(m => m.StaffID == staffid);

                //新房
                if (staffRolesList.Where(m => m.RoleID == 5).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_01 = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == model.Id && m.ModuleID == 1).FirstOrDefault();

                    IntermediaryStaffShowModel model1 = new IntermediaryStaffShowModel();
                    model1.IntermediaryID = model.Id;
                    model1.ModuleID = 1;
                    model1.ModuleName = "新房";
                    model1.SortID = 1;

                    if (intermediaryStaffModel_01 != null)
                    {
                        if (intermediaryStaffModel_01.StaffID == staffid)
                        {
                            model1.IsExistStaff = 3;//可弃管                        
                        }
                        else
                        {
                            model1.IsExistStaff = 2;//存在                        
                        }
                        model1.StaffName = StaffContract.GetByKey(intermediaryStaffModel_01.StaffID).Name;
                    }
                    else
                    {
                        model1.IsExistStaff = 1;//不存在
                        model1.StaffName = "";
                    }

                    query.IntermediaryStaffShowList.Add(model1);
                }

                //装修
                if (staffRolesList.Where(m => m.RoleID == 17).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_02 = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == model.Id && m.ModuleID == 4).FirstOrDefault();

                    IntermediaryStaffShowModel model2 = new IntermediaryStaffShowModel();
                    model2.IntermediaryID = model.Id;
                    model2.ModuleID = 4;
                    model2.ModuleName = "装修";
                    model2.SortID = 2;

                    if (intermediaryStaffModel_02 != null)
                    {
                        if (intermediaryStaffModel_02.StaffID == staffid)
                        {
                            model2.IsExistStaff = 3;//可弃管                        
                        }
                        else
                        {
                            model2.IsExistStaff = 2;//存在                        
                        }
                        model2.StaffName = StaffContract.GetByKey(intermediaryStaffModel_02.StaffID).Name;
                    }
                    else
                    {
                        model2.IsExistStaff = 1;//不存在
                        model2.StaffName = "";
                    }

                    query.IntermediaryStaffShowList.Add(model2);
                }

                //金融
                if (staffRolesList.Where(m => m.RoleID == 21).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_03 = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == model.Id && m.ModuleID == 5).FirstOrDefault();

                    IntermediaryStaffShowModel model3 = new IntermediaryStaffShowModel();
                    model3.IntermediaryID = model.Id;
                    model3.ModuleID = 5;
                    model3.ModuleName = "金融";
                    model3.SortID = 3;

                    if (intermediaryStaffModel_03 != null)
                    {
                        if (intermediaryStaffModel_03.StaffID == staffid)
                        {
                            model3.IsExistStaff = 3;//可弃管                        
                        }
                        else
                        {
                            model3.IsExistStaff = 2;//存在                        
                        }
                        model3.StaffName = StaffContract.GetByKey(intermediaryStaffModel_03.StaffID).Name;
                    }
                    else
                    {
                        model3.IsExistStaff = 1;//不存在
                        model3.StaffName = "";
                    }

                    query.IntermediaryStaffShowList.Add(model3);
                }


                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }


        [Description("API-上传执照图片")]
        public IHttpActionResult ttUploadLicenceImage([FromBody]LicenceImageParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }

            //门店信息
            var model = IntermediaryContract.GetByKey(entity.IntermediaryID);
            if (model == null)
            {
                var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }

            try
            {
                //处理图片字符串
                MemoryStream ms = new MemoryStream(Convert.FromBase64String(entity.Imagedata));
                byte[] bt = ms.ToArray();
                var oStream = new MemoryStream(bt);

                string m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                string m_savePath = "/Images/LicenceImages/";
                string m_exName = "jpg";

                if (Directory.Exists(BaseWebApiExt.GetMapPath(m_savePath)) == false)
                {
                    Directory.CreateDirectory(BaseWebApiExt.GetMapPath(m_savePath));
                }

                string m_fileName = m_saveName + "." + m_exName;

                System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
                img.Save(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName, ImageFormat.Jpeg);   //保存

                model.LicenceImage = m_savePath + m_fileName;//图片路径

                int count = IntermediaryContract.Update(model);

                if (count > 0)
                {
                    var result = new AjaxResult("上传成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("上传失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception ex)
            {
                var result = new AjaxResult("上传失败", AjaxResultType.Error);
                return Token(result, "");
            }
        }


        //经纪人列表==========================================================================================================

        [Description("API-经纪人列表")]
        public IHttpActionResult ttGetUsersList([FromBody]UsersParamsModel entity)
        {

            var query = from m in UsersContract.Entities
                        where m.IntermediaryID == entity.IntermediaryID && m.IsDeleted == false
                        select new UsersListModel
                        {
                            Id = m.Id,
                            Name = m.Name,
                            Sex = m.Sex,
                            Phone = m.Phone,
                            IntermediaryRoleID = (from m1 in UsersRolesContract.Entities where m1.UserID == m.Id && m1.IntermediaryRoleID == 1 select m1.Id).Count() > 0 ? 1 : 2
                        };

            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(m => m.Name.Contains(entity.KeyWord) || m.Phone.Contains(entity.KeyWord));
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Name);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<UsersListModel>().AsQueryable();// null;

            var result = new AjaxResult("成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");

        }


        //经纪人已存在==========================================================================================================

        [Description("API-验证电话")]
        public IHttpActionResult ttValidateUsersPhone([FromBody]Users entity)
        {
            var query = UsersContract.Entities.Where(m => m.Phone == entity.Phone && m.IsDeleted == false);

            if (query.Count() > 0)
            {

                //经纪人
                var userModel = query.FirstOrDefault();

                //中介
                var intermediaryModel = IntermediaryContract.GetByKey(userModel.IntermediaryID);

                //中介业务员
                var intermediaryStaffList = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == intermediaryModel.Id);

                //返回值
                IntermediaryAndUserShowModel showModel = new IntermediaryAndUserShowModel();
                showModel.IntermediaryName = intermediaryModel.Name;
                showModel.IntermediaryAddress = intermediaryModel.Address;
                showModel.UserName = userModel.Name;
                showModel.Sex = userModel.Sex;
                showModel.Phone = userModel.Phone;
                showModel.IntermediaryStaffShowList = new List<IntermediaryStaffShowModel>();

                //获取StaffID
                int staffid = BaseWebApiExt.GetStaffIDByToken();

                //角色集合
                var staffRolesList = StaffRolesContract.Entities.Where(m => m.StaffID == staffid);

                //新房
                if (staffRolesList.Where(m => m.RoleID == 5).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_01 = intermediaryStaffList.Where(m => m.ModuleID == 1).FirstOrDefault();

                    IntermediaryStaffShowModel model = new IntermediaryStaffShowModel();
                    model.IntermediaryID = intermediaryModel.Id;
                    model.ModuleID = 1;
                    model.ModuleName = "新房";
                    model.SortID = 1;

                    if (intermediaryStaffModel_01 != null)
                    {
                        model.IsExistStaff = 2;//存在                        
                        model.StaffName = StaffContract.GetByKey(intermediaryStaffModel_01.StaffID).Name;
                    }
                    else
                    {
                        model.IsExistStaff = 1;
                        model.StaffName = "";
                    }

                    showModel.IntermediaryStaffShowList.Add(model);
                }

                //装修
                if (staffRolesList.Where(m => m.RoleID == 17).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_02 = intermediaryStaffList.Where(m => m.ModuleID == 4).FirstOrDefault();

                    IntermediaryStaffShowModel model2 = new IntermediaryStaffShowModel();
                    model2.IntermediaryID = intermediaryModel.Id;
                    model2.ModuleID = 4;
                    model2.ModuleName = "装修";
                    model2.SortID = 2;

                    if (intermediaryStaffModel_02 != null)
                    {
                        model2.IsExistStaff = 2;//存在
                        model2.StaffName = StaffContract.GetByKey(intermediaryStaffModel_02.StaffID).Name;
                    }
                    else
                    {
                        model2.IsExistStaff = 1;//不存在
                        model2.StaffName = "";
                    }

                    showModel.IntermediaryStaffShowList.Add(model2);
                }

                //金融
                if (staffRolesList.Where(m => m.RoleID == 21).Count() > 0)//有权查看
                {
                    var intermediaryStaffModel_03 = intermediaryStaffList.Where(m => m.ModuleID == 5).FirstOrDefault();

                    IntermediaryStaffShowModel model3 = new IntermediaryStaffShowModel();
                    model3.IntermediaryID = intermediaryModel.Id;
                    model3.ModuleID = 5;
                    model3.ModuleName = "金融";
                    model3.SortID = 3;

                    if (intermediaryStaffModel_03 != null)
                    {
                        model3.IsExistStaff = 2;//存在
                        model3.StaffName = StaffContract.GetByKey(intermediaryStaffModel_03.StaffID).Name;
                    }
                    else
                    {
                        model3.IsExistStaff = 1;//不存在
                        model3.StaffName = "";
                    }

                    showModel.IntermediaryStaffShowList.Add(model3);
                }


                var result = new AjaxResult("已存在", AjaxResultType.Success, showModel);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("不存在", AjaxResultType.Error, new { });
                return Token(result, "");
            }
        }


        [Description("API-我要接管")]
        public IHttpActionResult ttHandleModule([FromBody]IntermediaryStaff entity)
        {
            //获取StaffID
            int staffid = BaseWebApiExt.GetStaffIDByToken();

            entity.StaffID = staffid;


            if (IsAuthorityModule(entity.ModuleID, entity.StaffID))//有权查看
            {
                //弃管
                if (IntermediaryStaffContract.Entities.Count(p => p.IntermediaryID == entity.IntermediaryID && p.ModuleID == entity.ModuleID && p.StaffID == staffid) > 0)
                {
                    IntermediaryStaffContract.DeleteDirect(p => p.IntermediaryID == entity.IntermediaryID && p.ModuleID == entity.ModuleID && p.StaffID == staffid);
                    var result = new AjaxResult("成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else //接管
                {
                    if (IntermediaryStaffContract.Entities.Count(p => p.IntermediaryID == entity.IntermediaryID && p.ModuleID == entity.ModuleID) == 0)
                    {
                        int count = IntermediaryStaffContract.Insert(entity);
                        if (count > 0)
                        {
                            var result = new AjaxResult("成功", AjaxResultType.Success);
                            return Token(result, "");
                        }
                        else
                        {
                            var result = new AjaxResult("失败", AjaxResultType.Error);
                            return Token(result, "");
                        }
                    }
                    else
                    {
                        var result = new AjaxResult("失败", AjaxResultType.Error);
                        return Token(result, "");
                    }
                }
            }
            else//无权查看
            {
                var result = new AjaxResult("无权接管", AjaxResultType.Error);
                return Token(result, "");
            }
        }


        //经纪人不存在==========================================================================================================


        [Description("API-类型集合")]
        public IHttpActionResult ttGetModulesList([FromBody]Staff entity)
        {
            //获取StaffID
            int staffid = BaseWebApiExt.GetStaffIDByToken();

            //角色集合
            var query = StaffRolesContract.Entities.Where(m => m.StaffID == staffid).ToList();

            List<Module> list = new List<Module>();

            //新房
            if (query.Where(m => m.RoleID == 5).Count() > 0)//有权查看
            {
                Module model = new Module();
                model.Id = 1;
                model.Name = "房产";
                list.Add(model);
            }
            //装修
            if (query.Where(m => m.RoleID == 17).Count() > 0)//有权查看
            {
                Module model = new Module();
                model.Id = 4;
                model.Name = "装修";
                list.Add(model);
            }
            //金融
            if (query.Where(m => m.RoleID == 21).Count() > 0)//有权查看
            {
                Module model = new Module();
                model.Id = 5;
                model.Name = "金融";
                list.Add(model);
            }

            var result = new AjaxResult("成功", AjaxResultType.Success, list);
            return Token(result, "");

        }


        [Description("API-添加门店(中介)和经纪人")]
        public IHttpActionResult ttInsertIntermediaryAndUser([FromBody]IntermediaryAndUserParamsModel entity)
        {
            var result = new AjaxResult("添加成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }
            if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State != 0 && p.IsDeleted == false) > 0)
            {
                result = new AjaxResult("已存在相同手机号", AjaxResultType.Error);
                return Token(result, "");
            }
            //获取StaffID
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            var staffModel = StaffContract.GetByKey(staffid);
            if (!IsAuthorityModule(entity.ModuleID, staffModel.Id))//有权查看
            {
                result = new AjaxResult("无权接管", AjaxResultType.Error);
                return Token(result, "");
            }

            var agentCityModel = AgentCityContract.Entities.Where(m => m.AgentID == staffModel.AgentID).FirstOrDefault();

            //门店
            Intermediary intermediaryModel = new Intermediary();
            intermediaryModel.Name = entity.IntermediaryName;
            intermediaryModel.Address = entity.IntermediaryAddress;
            intermediaryModel.CreateTime = DateTime.Now;
            intermediaryModel.AgentID = staffModel.AgentID;

            //门店类型
            IntermediaryStaff intermediaryStaffModel = new IntermediaryStaff();
            intermediaryStaffModel.ModuleID = entity.ModuleID;
            intermediaryStaffModel.StaffID = staffModel.Id;

            //经纪人
            Users usersModel = new Users();
            usersModel.Name = entity.UserName;
            usersModel.Sex = entity.Sex;
            usersModel.Phone = entity.Phone;
            usersModel.Declaration = entity.Declaration;
            usersModel.OperationPeriod = entity.OperationPeriod;
            usersModel.CityID = (agentCityModel == null) ? "" : agentCityModel.CityID;

            //经纪人登陆表
            UsersLogin usersLoginModel = new UsersLogin();
            int count = 0;
            if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
            {
                usersLoginModel = UsersLoginContract.Entities.FirstOrDefault(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false);
                usersLoginModel.State = 1;
            }
            else
            {
                usersLoginModel.LoginName = entity.Phone;
                usersLoginModel.LoginPass = "123456";
                usersLoginModel.LoginType = 1;
                usersLoginModel.State = 1;
                usersLoginModel.SMSCodeID = 0;
            }

            //经纪人角色
            UsersRoles usersRolesModel = new UsersRoles();
            usersRolesModel.IntermediaryRoleID = 1;//默认角色为店长


            //事务开始
            IntermediaryContract.Repository.UnitOfWork.BeginTransaction();

            //新增 门店
            count += IntermediaryContract.Insert(intermediaryModel);

            //新增 门店类型
            if (count == 1)
            {
                    intermediaryStaffModel.IntermediaryID = intermediaryModel.Id;
                    count += IntermediaryStaffContract.Insert(intermediaryStaffModel);
            }

            //新增 经纪人
            if (count == 2)
            {
                usersModel.IntermediaryID = intermediaryModel.Id;
                count += UsersContract.Insert(usersModel);
            }

            //新增 经纪人登陆表
            if (count == 3)
            {
                usersLoginModel.UserID = usersModel.Id;
                if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
                {
                    count += UsersLoginContract.Update(usersLoginModel);
                }
                else
                {
                    count += UsersLoginContract.Insert(usersLoginModel);
                }
            }

            //新增 经纪人角色  
            if (count == 4)
            {
                usersRolesModel.UserID = usersModel.Id;
                count += UsersRolesContract.Insert(usersRolesModel);
            }

            //事务结束
            IntermediaryContract.Repository.UnitOfWork.Commit();

            if (count < 5)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }

            return Token(result, "");
        }


        [Description("API-添加经纪人")]
        public IHttpActionResult ttInsertNewUser([FromBody]Users entity)
        {
            var result = new AjaxResult("添加成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }
            if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State != 0 && p.IsDeleted == false) > 0)
            {
                result = new AjaxResult("已存在相同手机号", AjaxResultType.Error);
                return Token(result, "");
            }

            try
            {
                //获取StaffID
                int staffid = BaseWebApiExt.GetStaffIDByToken();
                var staffModel = StaffContract.GetByKey(staffid);
                var agentCityModel = AgentCityContract.Entities.Where(m => m.AgentID == staffModel.AgentID).FirstOrDefault();

                //经纪人
                Users usersModel = entity;
                usersModel.CityID = (agentCityModel == null) ? "" : agentCityModel.CityID;

                //经纪人登陆表
                UsersLogin usersLoginModel = new UsersLogin();
                int count = 0;
                if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
                {
                    usersLoginModel = UsersLoginContract.Entities.FirstOrDefault(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false);
                    usersLoginModel.State = 1;
                }
                else
                {
                    usersLoginModel.LoginName = entity.Phone;
                    usersLoginModel.LoginPass = "123456";
                    usersLoginModel.LoginType = 1;
                    usersLoginModel.State = 1;
                    usersLoginModel.SMSCodeID = 0;
                }

                //事务开始
                IntermediaryContract.Repository.UnitOfWork.BeginTransaction();
                //新增 经纪人
                count = UsersContract.Insert(usersModel);
                if (count > 0)
                {
                    //新增 经纪人登陆表
                    usersLoginModel.UserID = usersModel.Id;
                    if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
                    {
                        count = UsersLoginContract.Update(usersLoginModel);
                    }
                    else
                    {
                        count = UsersLoginContract.Insert(usersLoginModel);
                    }
                    if (count > 0)
                    {
                        result = new AjaxResult("添加成功", AjaxResultType.Success);
                    }
                    else
                    {
                        result = new AjaxResult("添加失败", AjaxResultType.Error);
                        IntermediaryContract.Repository.UnitOfWork.Rollback();
                    }
                }
                else
                {
                    result = new AjaxResult("添加失败", AjaxResultType.Error);
                    IntermediaryContract.Repository.UnitOfWork.Rollback();

                }

                //事务结束
                IntermediaryContract.Repository.UnitOfWork.Commit();
            }
            catch (Exception ex)
            {
                result = new AjaxResult("操作异常", AjaxResultType.Error);
            }

            return Token(result, "");
        }


        //公共方法==========================================================================================================

        private bool IsAuthorityModule(int ModuleID, int StaffID)
        {
            //角色集合
            var staffRolesList = StaffRolesContract.Entities.Where(m => m.StaffID == StaffID);

            //验证角色
            if (ModuleID == 1 && staffRolesList.Where(m => m.RoleID == 5).Count() > 0)
            {
                return true;//新房
            }
            if (ModuleID == 4 && staffRolesList.Where(m => m.RoleID == 17).Count() > 0)
            {
                return true;//装修
            }
            if (ModuleID == 5 && staffRolesList.Where(m => m.RoleID == 21).Count() > 0)
            {
                return true;//金融
            }

            return false;//无权接管
        }


        //考勤打卡==========================================================================================================


        [Description("API-内勤打卡")]
        public IHttpActionResult ttInSide([FromBody]SideParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }

            MemoryStream ms = new MemoryStream(Convert.FromBase64String(entity.Imagedata));
            byte[] bt = ms.ToArray();
            var oStream = new MemoryStream(bt);

            string m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
            string m_savePath = "/Images/SideImage/";
            string m_exName = "jpg";


            if (Directory.Exists(BaseWebApiExt.GetMapPath(m_savePath)) == false)
            {
                Directory.CreateDirectory(BaseWebApiExt.GetMapPath(m_savePath));
            }


            System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
            if (img.RawFormat.Guid.Equals(ImageFormat.Jpeg.Guid))
            {
                m_exName = "jpg";
            }
            else if (img.RawFormat.Guid.Equals(ImageFormat.Png.Guid))
            {
                m_exName = "png";
            }
            else if (img.RawFormat.Guid.Equals(ImageFormat.Gif.Guid))
            {
                m_exName = "gif";
            }
            else
            {
                var result = new AjaxResult("文件格式错误", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }
            string m_fileName = m_saveName + "." + m_exName;

            while (File.Exists(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName))
            {
                System.Threading.Thread.Sleep(1);
                m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                m_fileName = m_saveName + "." + m_exName;
            }


            img.Save(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName, img.RawFormat);   //保存

            int staffid = BaseWebApiExt.GetStaffIDByToken();
            var staffmodel = StaffContract.GetByKey(staffid);
            var sidemodule = SideModuleContract.GetByKey(staffmodel.SideModuleID);
            sidemodule.StartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + sidemodule.StartTime.ToString("HH:mm:ss"));
            sidemodule.EndTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + sidemodule.EndTime.ToString("HH:mm:ss"));
            InSideModel model = new InSideModel();
            int count = 0;
            if (InSideModelContract.Entities.AsEnumerable().Count(p => p.CreatorId == staffid.ToString() && p.CreatedTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")) == 0)
            {
                switch (entity.SideType)
                {
                    case 1:
                        model = new InSideModel()
                        {
                            CreatedTime = DateTime.Now,
                            CreatorId = staffid.ToString(),
                            EndContent = "",
                            EndImagePage = "",
                            EndLatitude = 0,
                            EndLeaveType = 0,
                            EndLocation = "",
                            EndLongitude = 0,
                            EndTime = DateTime.Now,
                            IsDeleted = false,
                            IsLocked = false,
                            StartContent = entity.SideContent,
                            StartImagePage = m_fileName,
                            StartLatitude = entity.Latitude,
                            StartLeaveType = DateTime.Now <= sidemodule.StartTime ? 1 : 2,
                            StartLocation = entity.Location,
                            StartLongitude = entity.Longitude,
                            StartTime = DateTime.Now
                        };
                        break;
                    case 2:
                        model = new InSideModel()
                        {
                            CreatedTime = DateTime.Now,
                            CreatorId = staffid.ToString(),
                            EndContent = entity.SideContent,
                            EndImagePage = m_fileName,
                            EndLatitude = entity.Latitude,
                            EndLeaveType = DateTime.Now >= sidemodule.EndTime ? 1 : 3,
                            EndLocation = entity.Location,
                            EndLongitude = entity.Longitude,
                            EndTime = DateTime.Now,
                            IsDeleted = false,
                            IsLocked = false,
                            StartContent = "",
                            StartImagePage = "",
                            StartLatitude = 0,
                            StartLeaveType = 0,
                            StartLocation = "",
                            StartLongitude = 0,
                            StartTime = DateTime.Now
                        };
                        break;
                    default:
                        break;
                }
                count = InSideModelContract.Insert(model);
            }
            else
            {
                model = InSideModelContract.Entities.AsEnumerable().Where(p => p.CreatorId == staffid.ToString() && p.CreatedTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault();
                switch (entity.SideType)
                {
                    case 1:
                        model.StartContent = entity.SideContent;
                        model.StartImagePage = m_fileName;
                        model.StartLatitude = entity.Latitude;
                        model.StartLeaveType = (DateTime.Now <= sidemodule.StartTime ? 1 : 2);
                        model.StartLocation = entity.Location;
                        model.StartLongitude = entity.Longitude;
                        model.StartTime = DateTime.Now;
                        break;
                    case 2:
                        model.EndContent = entity.SideContent;
                        model.EndImagePage = m_fileName;
                        model.EndLatitude = entity.Latitude;
                        model.EndLeaveType = (DateTime.Now >= sidemodule.EndTime ? 1 : 3);
                        model.EndLocation = entity.Location;
                        model.EndLongitude = entity.Longitude;
                        model.EndTime = DateTime.Now;
                        break;
                    default:
                        break;
                }
                count = InSideModelContract.Update(model);
            }



            if (count > 0)
            {
                var result = new AjaxResult("成功", AjaxResultType.Success, model);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }


        [Description("API-外勤打卡")]
        public IHttpActionResult ttOutSide([FromBody]SideParamsModel entity)
        {
            try
            {

                if (entity == null)
                {
                    var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                    return Token(result, "");
                }

                MemoryStream ms = new MemoryStream(Convert.FromBase64String(entity.Imagedata));
                byte[] bt = ms.ToArray();
                var oStream = new MemoryStream(bt);

                string m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                string m_savePath = "/Images/SideImage/";
                string m_exName = "jpg";


                if (Directory.Exists(BaseWebApiExt.GetMapPath(m_savePath)) == false)
                {
                    Directory.CreateDirectory(BaseWebApiExt.GetMapPath(m_savePath));
                }


                System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
                if (img.RawFormat.Guid.Equals(ImageFormat.Jpeg.Guid))
                {
                    m_exName = "jpg";
                }
                else if (img.RawFormat.Guid.Equals(ImageFormat.Png.Guid))
                {
                    m_exName = "png";
                }
                else if (img.RawFormat.Guid.Equals(ImageFormat.Gif.Guid))
                {
                    m_exName = "gif";
                }
                else
                {
                    var result = new AjaxResult("文件格式错误", AjaxResultType.Error, new object[] { });
                    return Token(result, "");
                }
                string m_fileName = m_saveName + "." + m_exName;

                while (File.Exists(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName))
                {
                    System.Threading.Thread.Sleep(1);
                    m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                    m_fileName = m_saveName + "." + m_exName;
                }


                img.Save(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName, img.RawFormat);   //保存

                int staffid = BaseWebApiExt.GetStaffIDByToken();
                //var staffmodel = StaffContract.GetByKey(staffid);
                //var sidemodule = SideModuleContract.GetByKey(staffmodel.SideModuleID);
                OutSideModel model = new OutSideModel();
                int count = 0;
                model = new OutSideModel()
                {
                    CreatedTime = DateTime.Now,
                    CreatorId = staffid.ToString(),
                    IsDeleted = false,
                    IsLocked = false,
                    OutSideContent = entity.SideContent,
                    ImagePage = m_fileName,
                    Latitude = entity.Latitude,
                    OutSideType = entity.SideType,
                    Location = entity.Location,
                    Longitude = entity.Longitude,
                    InterfixID = entity.InterfixID,
                    NewHouseEvaluate = entity.NewHouseEvaluate,
                    Origin = entity.Origin,
                    OtherEvaluate = entity.OtherEvaluate,
                    Receiver = entity.Receiver
                };
                count = OutSideModelContract.Insert(model);


                if (count > 0)
                {
                    var result = new AjaxResult("成功", AjaxResultType.Success, model);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception e)
            {
                var result = new AjaxResult(e.Message, AjaxResultType.Error);
                return Token(result, "");
            }

        }


        [Description("API-外勤列表")]
        public IHttpActionResult ttGetOutSideList([FromBody]SideParamsModel entity)
        {
            //获取StaffID
            string staffid = BaseWebApiExt.GetStaffIDByToken().ToString();

            //角色集合
            var query = from a in OutSideModelContract.Entities
                        where a.CreatorId == staffid && a.InterfixID == entity.InterfixID && a.OutSideType == entity.SideType && !a.IsDeleted
                        select new
                        {
                            CreatedTime = a.CreatedTime,
                            CreatorId = a.CreatorId,
                            Id = a.Id,
                            ImagePage = "/Images/SideImage/" + a.ImagePage,
                            InterfixID = a.InterfixID,
                            IsDeleted = a.IsDeleted,
                            IsLocked = a.IsLocked,
                            Latitude = a.Latitude,
                            Location = a.Location,
                            Longitude = a.Longitude,
                            OutSideContent = a.OutSideContent,
                            OutSideType = a.OutSideType,
                        };


            var result = new AjaxResult("成功", AjaxResultType.Success, query.OrderByDescending(p => p.Id).ToList());
            return Token(result, "");

        }
        [Description("API-外勤列表")]
        public IHttpActionResult ttGetOutSideListForAll([FromBody]OutSideParamsModel entity)
        {


            //角色集合
            var query = from a in OutSideModelContract.Entities
                        where a.OutSideType == entity.SideType && !a.IsDeleted && a.CreatedTime >= entity.BeginTime && a.CreatedTime <= entity.EndTime
                        select new
                        {
                            CreatedTime = a.CreatedTime,
                            CreatorId = a.CreatorId,
                            Id = a.Id,
                            ImagePage = "/Images/SideImage/" + a.ImagePage,
                            InterfixID = a.InterfixID,
                            IsDeleted = a.IsDeleted,
                            IsLocked = a.IsLocked,
                            Latitude = a.Latitude,
                            Location = a.Location,
                            Longitude = a.Longitude,
                            OutSideContent = a.OutSideContent,
                            OutSideType = a.OutSideType,
                        };


            var result = new AjaxResult("成功", AjaxResultType.Success, query.OrderByDescending(p => p.Id).ToList());
            return Token(result, "");

        }

        [Description("API-内勤列表")]
        public IHttpActionResult ttGetSignSideListSelf([FromBody]OutSideParamsModel entity)
        {
            //获取StaffID
            string staffid = BaseWebApiExt.GetStaffIDByToken().ToString();
            entity.EndTime = Convert.ToDateTime(entity.EndTime.ToShortDateString() + " 23:59:59");
            //角色集合
            var query = (from a in InSideModelContract.Entities.AsEnumerable()
                         where a.CreatorId == staffid && !a.IsDeleted && a.CreatedTime >= entity.BeginTime && a.CreatedTime <= entity.EndTime && a.StartLeaveType!=0
                         select new
                         {
                             Type = 0,
                             Time = a.StartTime,
                             Id = a.Id,
                             ImagePage = "/Images/SideImage/" + a.StartImagePage,
                             Location = a.StartLocation,
                             Remark = a.StartContent,
                         })
                         .Union(from a in InSideModelContract.Entities.AsEnumerable()
                                where a.CreatorId == staffid && !a.IsDeleted && a.CreatedTime >= entity.BeginTime && a.CreatedTime <= entity.EndTime && a.EndLeaveType != 0
                                select new
                                {
                                    Type = 1,//下班卡
                                    Time = a.EndTime,//打卡时间
                                    Id = a.Id,
                                    ImagePage = "/Images/SideImage/" + a.EndImagePage,//图片
                                    Location = a.EndLocation,//地址
                                    Remark = a.EndContent,//备注
                                })
                        .Union(from a in OutSideModelContract.Entities.AsEnumerable()
                               where a.CreatorId == staffid && a.OutSideType == 1 && !a.IsDeleted && a.CreatedTime >= entity.BeginTime && a.CreatedTime <= entity.EndTime
                               select new
                               {
                                   Type = -1,//下班卡
                                   Time = a.CreatedTime,
                                   Id = a.Id,
                                   ImagePage = "/Images/SideImage/" + a.ImagePage,
                                   Location = a.Location,
                                   Remark = a.OutSideContent,
                               });


            var result = new AjaxResult("成功", AjaxResultType.Success, query.OrderByDescending(p => p.Time).ToList());
            return Token(result, "");

        }

        [Description("API-通讯录")]
        public IHttpActionResult ttGetContact([FromBody]Contacts entity)
        {

            var query = (from d in DepartmentContract.Entities
                         select new Contacts
                         {
                             DepartmentID = d.Id,
                             DepartmentName = d.Name,

                         }).ToList();
            foreach (var item in query)
            {
                item.StaffList = new List<NamePhone>();
                var list = StaffContract.Entities.Where(m => !m.IsDeleted && m.DepartmentID == item.DepartmentID).ToList();
                foreach (var itemi in list)
                {
                    item.StaffList.Add(new NamePhone() { Name = itemi.Name, Phone = itemi.Phone });
                }

            }

            var result = new AjaxResult("成功", AjaxResultType.Success, query);
            return Token(result, "");

        }

        [Description("API-消息")]
        public IHttpActionResult ttGetStaffMessages([FromBody]BuildingsParamsModel entity)
        {
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            var staffmodel = StaffContract.GetByKey(staffid);

            var query = StaffMessagesContract.Entities.Where(p => !p.IsDeleted && p.StaffID == staffid);
            query = query.OrderByDescending(p => p.Id);
            //数据总数
            var total = query.Count();


            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<StaffMessages>().AsQueryable(); ;// null;

            var result = new AjaxResult("成功", AjaxResultType.Success, query);
            return Token(result, "");
        }
        [Description("API-修改消息状态")]
        public IHttpActionResult ttModifyStaffMessagesState([FromBody]StaffMessages entity)
        {
            StaffMessages m = StaffMessagesContract.GetByKey(entity.Id);
            m.State = 2;
            StaffMessagesContract.Update(m);

            var result = new AjaxResult("成功", AjaxResultType.Success, "");
            return Token(result, "");
        }

        [Description("API-添加门店(中介)和经纪人")]
        [AllowAnonymous]
        public IHttpActionResult ttInsertIntermediaryAndUserForOldSys([FromBody]IntermediaryAndUserParamsModel entity)
        {
            var result = new AjaxResult("添加成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }
            if (StaffContract.Entities.Count(p => p.OldID == entity.OldUserID) == 0)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }
            if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State != 0 && p.IsDeleted == false) > 0)
            {
                result = new AjaxResult("已存在相同手机号", AjaxResultType.Error);
                return Token(result, "");
            }

            //获取StaffID
            int staffid = StaffContract.Entities.FirstOrDefault(p => p.OldID == entity.OldUserID).Id;
            var staffModel = StaffContract.GetByKey(staffid);
            var agentCityModel = AgentCityContract.Entities.Where(m => m.AgentID == staffModel.AgentID).FirstOrDefault();
            if (!IsAuthorityModule(entity.ModuleID, staffModel.Id))//有权查看
            {
                result = new AjaxResult("无权接管", AjaxResultType.Error);
                return Token(result, "");
            }

            //门店
            Intermediary intermediaryModel = new Intermediary();
            intermediaryModel.Name = entity.IntermediaryName;
            intermediaryModel.Address = entity.IntermediaryAddress;
            intermediaryModel.CreateTime = DateTime.Now;

            //门店类型
            IntermediaryStaff intermediaryStaffModel = new IntermediaryStaff();
            intermediaryStaffModel.ModuleID = entity.ModuleID;
            intermediaryStaffModel.StaffID = staffModel.Id;

            //经纪人
            Users usersModel = new Users();
            usersModel.Name = entity.UserName;
            usersModel.Sex = entity.Sex;
            usersModel.Phone = entity.Phone;
            usersModel.Declaration = entity.Declaration;
            usersModel.OperationPeriod = entity.OperationPeriod;
            usersModel.CityID = (agentCityModel == null) ? "" : agentCityModel.CityID;

            //经纪人登陆表
            UsersLogin usersLoginModel = new UsersLogin();
            int count = 0;
            if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
            {
                usersLoginModel = UsersLoginContract.Entities.FirstOrDefault(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false);
                usersLoginModel.State = 1;
            }
            else
            {
                usersLoginModel.LoginName = entity.Phone;
                usersLoginModel.LoginPass = "123456";
                usersLoginModel.LoginType = 1;
                usersLoginModel.State = 1;
                usersLoginModel.SMSCodeID = 0;
            }

            //经纪人角色
            UsersRoles usersRolesModel = new UsersRoles();
            usersRolesModel.IntermediaryRoleID = 1;//默认角色为店长


            //事务开始
            IntermediaryContract.Repository.UnitOfWork.BeginTransaction();

            //新增 门店
            count += IntermediaryContract.Insert(intermediaryModel);

            //新增 门店类型
            if (count == 1)
            {
                intermediaryStaffModel.IntermediaryID = intermediaryModel.Id;
                count += IntermediaryStaffContract.Insert(intermediaryStaffModel);
            }

            //新增 经纪人
            if (count == 2)
            {
                usersModel.IntermediaryID = intermediaryModel.Id;
                count += UsersContract.Insert(usersModel);
            }

            //新增 经纪人登陆表
            if (count == 3)
            {
                usersLoginModel.UserID = usersModel.Id;
                if (UsersLoginContract.Entities.Count(p => p.LoginName == entity.Phone && p.State == 0 && p.IsDeleted == false) > 0)
                {
                    count += UsersLoginContract.Update(usersLoginModel);
                }
                else
                {
                    count += UsersLoginContract.Insert(usersLoginModel);
                }

            }

            //新增 经纪人角色  
            if (count == 4)
            {
                usersRolesModel.UserID = usersModel.Id;
                count += UsersRolesContract.Insert(usersRolesModel);
            }

            //事务结束
            IntermediaryContract.Repository.UnitOfWork.Commit();

            if (count < 5)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                IntermediaryContract.Repository.UnitOfWork.Rollback();
                return Token(result, "");
            }

            return Token(result, "");
        }

    }
}
